package com.ruoyi.system.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.common.wx.config.WxMaConfiguration;
import com.ruoyi.system.form.LoginBody;
import com.ruoyi.system.form.RegisterBody;
import com.ruoyi.system.service.SysLoginService;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController extends BaseController {

    @Autowired
    private TokensService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RedisService redisService;

    @PostMapping("login")
    @ApiOperation("用户登录（需传入账号密码）\n" +
            "(username-账号-String-必填),\n" +
            "(password-密码-String-必填")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @GetMapping("wx-app-login")
    public AjaxResult wxAppLogin(@RequestParam("code") String code) {
        //小程序登录
        if (StringUtils.isBlank(code)) {
            return error("缺失code,登录失败！");
        }
        final WxMaService wxService = WxMaConfiguration.getMaService();

        try {
            /*File cls001 = wxService.getQrcodeService().createWxaCodeUnlimit("CLS001" , "pages/index/index");

            byte[] data = null;
            // 读取图片字节数组
            try {
                FileInputStream inputStream =new FileInputStream(cls001);
                inputStream.read(data);
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 对字节数组进行Base64编码，得到Base64编码的字符串
            BASE64Encoder encoder = new BASE64Encoder();
            String base64Str = encoder.encode(data);
            System.out.println(base64Str);*/

            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            // 用户登录
            LoginUser userInfo = sysLoginService.wxAppLogin(session.getOpenid());
            userInfo.setSessionKey(session.getSessionKey());
            tokenService.createToken(userInfo);
            String accessToken = wxService.getAccessToken();
            System.out.println(accessToken);
            return AjaxResult.success(userInfo);

        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return error(e.getMessage());
        }
    }

    @DeleteMapping("logout")
    @ApiOperation("用户退出登录")
    public R<?> logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String username = loginUser.getUsername();
            // 从redis缓存中清除记录
            redisService.deleteObject(loginUser.getToken());
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    @ApiOperation("用户注册（需传入账号密码）\n" +
            "(username-账号-String-必填),\n" +
            "(password-密码-String-必填)")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

}
